package cn.cvs.controller;

import cn.cvs.pojo.SysDept;
import cn.cvs.service.SysDeptService;
import cn.cvs.utils.TableVO;
import cn.cvs.utils.TreeVO;
import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/dept")
public class DeptController {

    @Autowired
    private SysDeptService sysDeptService;


    @GetMapping("/list2")
    public String list2(){
        return "sysDept/list";
    }

    @GetMapping(value = "/list",produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public String list(Integer page,Integer limit){

        List<SysDept> deptList = sysDeptService.deptAll(page,limit);

        int count = sysDeptService.count();

        TableVO tableVO = new TableVO(0, count, deptList, "");

        String json = JSON.toJSONString(tableVO);

        return json;
    }


    //树形菜单 根节点
    @RequestMapping(value = "/tree", produces = {"application/json;charset=utf-8"})
    @ResponseBody
    public String treeMenu() {

        TreeVO treeVO = new TreeVO();

        //根节点
        SysDept sysDept = sysDeptService.topDept(0);
        treeVO.setTitle(sysDept.getDeptName());
        treeVO.setId(sysDept.getDeptId());

        TreeVO treeVO1 = null;

        //拿到除根节点的所有数据
        List<SysDept> list = sysDeptService.children(sysDept.getDeptId());
        List<TreeVO> treeVOS = new ArrayList<>();
        for (SysDept dept : list) {
            int deptId = sysDept.getDeptId();
            int parentId = dept.getParentId();
            if (deptId == parentId){
                treeVO1 = new TreeVO();
                //找到根节点菜单的时候，寻找这个根节点菜单下的子节点菜单。
                treeVO1.setTitle(dept.getDeptName());
                treeVO1.setId(dept.getDeptId());
                treeVO1.setChildren(children(dept));
            }
            treeVOS.add(treeVO1);
        }
        treeVO.setChildren(treeVOS);

        String json = JSON.toJSONString(treeVO);

        return json;
    }

    /**
     * 遍历子级
     *
     * @param sysDept 父级
     * @return 子级集合
     */
    public List<TreeVO> children(SysDept sysDept) {
        List<TreeVO> objects = new ArrayList<>();

        TreeVO treeVO = null;
        //遍历所有数据，找到是入参父节点的子节点的数据，然后加到childrenList集合中。
        for (SysDept dept : sysDeptService.children(sysDept.getDeptId())) {
            int deptId = sysDept.getDeptId();
            int parentId = dept.getParentId();
            if (deptId == parentId) {
                treeVO = new TreeVO();
                treeVO.setTitle(dept.getDeptName());
                treeVO.setId(dept.getDeptId());
            }
            objects.add(treeVO);
        }

        return objects;
    }

}
